﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace Common
{
    /// <summary>
    /// 拷贝帮助类
    /// </summary>
    public class CopyHelper
    {
        /// <summary>
        /// 深拷贝（单体）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static T DeepCopy<T>(T source)
        {
            if (source is string || source.GetType().IsValueType)
                return source;

            object retval = Activator.CreateInstance(source.GetType());
            FieldInfo[] fields = source.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
            foreach (var field in fields)
            {
                field.SetValue(retval, DeepCopy(field.GetValue(source)));
            }
            return (T)retval;
        }

        /// <summary>
        /// 深拷贝（集合）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static List<T> DeepCopy<T>(List<T> source)
        {
            List<T> result = new List<T>();

            foreach (var item in source)
            {
                result.Add(DeepCopy(item));
            }

            return result;
        }
    }
}
